package com.newworld.dmsapp2.register;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.newworld.dmsapp2.BaseActivity;
import com.newworld.dmsapp2.R;
import com.newworld.dmsapp2.activity.serviceapply.WriteOutdoorPaperActivity;
import com.newworld.dmsapp2.bean.User;
import com.newworld.dmsapp2.util.Config;
import com.newworld.dmsapp2.util.HttpUtil;
import com.newworld.dmsapp2.util.SingleSample;
import com.newworld.dmsapp2.util.Tool;

public class HouseChooseReuseActivity extends BaseActivity implements
		OnClickListener {
	private ListView buildLv;
	private ArrayAdapter<String> adapter;
	private TextView titleBarTv;
	private LinearLayout leftLayout;
	private ProgressBar getBulidProbar;
	
	private List<Map<String, String>> requestList = new ArrayList<Map<String, String>>();
	private Intent intent;
	private String levelCode;
	private String levelObjectId;
	private String houseFullName;
	private String titlestr = "";
	private String sessionId;

	private boolean publicflag = WriteOutdoorPaperActivity.PUBLIC_FLAG;
	
	Handler mHandler = new Handler(){
		@SuppressWarnings("unchecked")
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case Config.HANDLER_MSG_GETHOUSE_SUCCESS:
				
				requestList = (List<Map<String, String>>) msg.obj;
				List<String> NameList = new ArrayList<String>();
				for (int i = 0; i < requestList.size(); i++) {
					Map<String,String> itemmap = requestList.get(i);
					if(null != itemmap.get("phaseName") && !itemmap.get("phaseName").equals("")){
						NameList.add(itemmap.get("phaseName"));
					}else if(null != itemmap.get("buildingName") && !itemmap.get("buildingName").equals("")){
						NameList.add(itemmap.get("buildingName"));
					}else if(null != itemmap.get("unitName") && !itemmap.get("unitName").equals("")){
						NameList.add(itemmap.get("unitName"));
					}else if(null != itemmap.get("floorName") && !itemmap.get("floorName").equals("")){
						NameList.add(itemmap.get("floorName"));
					}else if(null != itemmap.get("houseName") && !itemmap.get("houseName").equals("")){
						NameList.add(itemmap.get("houseName"));
					}
				}
				titleBarTv.setText(titlestr);
				adapter = new ArrayAdapter<String>(
						HouseChooseReuseActivity.this, R.layout.list_ok,
						NameList);
				buildLv.setAdapter(adapter);
				adapter.notifyDataSetChanged();
				getBulidProbar.setVisibility(View.INVISIBLE);
				Toast.makeText(HouseChooseReuseActivity.this, "加载成功", Toast.LENGTH_SHORT).show();
			
				break;
			case Config.HANDLER_MSG_GETHOUSE_FAIL:
				getBulidProbar.setVisibility(View.INVISIBLE);
				Toast.makeText(HouseChooseReuseActivity.this, (String) msg.obj, Toast.LENGTH_SHORT).show();
				break;
			default:
				break;
			}
		};
		
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_register_house_choose_list1);
		initData();
		initViews();
		initEvents();
	}

	@Override
	protected void initViews() {
		titleBarTv = (TextView) findViewById(R.id.titlebar_left_center_title);

		leftLayout = (LinearLayout) findViewById(R.id.titlebar_left_left_layout);
		buildLv = (ListView) findViewById(R.id.house_choose_list);
		getBulidProbar = (ProgressBar) findViewById(R.id.proBar_get_data);
		
		if (Tool.isNetworkAvailable(HouseChooseReuseActivity.this)) {
			Thread getdataThread = new getDataThread(levelCode, levelObjectId);
			getdataThread.start();
		} else {
			Toast.makeText(HouseChooseReuseActivity.this, "请检查网络连接！",
					Toast.LENGTH_SHORT).show();
		}
		
	}

	private void initData(){
		intent = getIntent();
		if (intent != null) {
			levelCode = "phase";
			levelObjectId = intent.getStringExtra("projectID");
			titlestr = "选择房屋";
			if(publicflag){
				houseFullName = intent.getStringExtra("cityName") 
						+ intent.getStringExtra("projectName");
			}else{
				houseFullName = "";
			}
			
		}
		
		User user = SingleSample.getInstance(this).getUser();
		if(null != user){
			if(null != user.getSessionId() && !user.getSessionId().equals("")){
				sessionId = user.getSessionId();
			}
		}
		
	}
	class getDataThread extends Thread{
		private String levelCode;
		private String levelObjectId;
		public getDataThread(String levelCode, String levelObjectId) {
			// TODO Auto-generated constructor stub
			this.levelCode = levelCode;
			this.levelObjectId = levelObjectId;
		}
		
		@SuppressWarnings("unchecked")
		@Override
		public void run() {

			if (Tool.isNetworkAvailable(HouseChooseReuseActivity.this)) {
				try {
					String result = "";
					String message = "";
					Map<String, String> map = new HashMap<String, String>();
					// 注册获取单元
					if (UserMessageActivity.INTENT_FLAG == 0 && !publicflag) {
						//map.put("functionCode",Config.INDOOR_GETDATA_FUNCTIONCODE);
						map.put("typeCode", Config.AREACODE_INDOOR+","+Config.AREACODE_BUSINESS);
					}

					// 关联获取单元
					else if (UserMessageActivity.INTENT_FLAG == 1 && !publicflag) {
						//map.put("functionCode",Config.INDOOR_GETDATA_FUNCTIONCODE);
						map.put("typeCode", Config.AREACODE_INDOOR+","+Config.AREACODE_BUSINESS);
					}
					//公区
					else if (publicflag) {
						map.put("typeCode", Config.AREACODE_OUTDOOR);
					
					}
					map.put("levelCode", levelCode);
					map.put("levelObjectId", levelObjectId);
					
					Log.e("levelCode》", levelCode);
					result = HttpUtil.postRequestSe(Tool.getConfigUrl(Config.SERVER_URL, Config.GETHOUSE_NEW_URL),
							 map,sessionId);
					Log.e("result》", result);
					
					JSONObject jsonobj = new JSONObject(result);
					
					message = jsonobj.getString("message").toString();
					if (jsonobj.getString("flag").equals("success")) {
						requestList.clear();
						if(result.contains("phaseLevel")){
							String phases = jsonobj.getString("phaseLevel");
							JSONArray jsonArray = new JSONArray(phases);
							for (int i = 0; i < jsonArray.length(); i++) {
								JSONObject jsonObject = jsonArray
										.getJSONObject(i);
								HashMap<String, String> buildMap = new HashMap<String, String>();
								Iterator<String> iterator = jsonObject.keys();
								while (iterator.hasNext()) {
									String key = iterator.next();
									String value = jsonObject.get(key) + "";
									buildMap.put(key, value);
								}
								requestList.add(buildMap);
						}

						}
						
						if(result.contains("buildingLevel")){
							String buildings = jsonobj.getString("buildingLevel");
							JSONArray jsonArray = new JSONArray(buildings);
							for (int i = 0; i < jsonArray.length(); i++) {
								JSONObject jsonObject = jsonArray
										.getJSONObject(i);
								HashMap<String, String> buildMap = new HashMap<String, String>();
								Iterator<String> iterator = jsonObject.keys();
								while (iterator.hasNext()) {
									String key = iterator.next();
									String value = jsonObject.get(key) + "";
									buildMap.put(key, value);
								}
								requestList.add(buildMap);
							}
						}
							
							if(result.contains("unitLevel")){
								String units = jsonobj.getString("unitLevel");
								JSONArray jsonArray = new JSONArray(units);
								for (int i = 0; i < jsonArray.length(); i++) {
									JSONObject jsonObject = jsonArray
											.getJSONObject(i);
									HashMap<String, String> buildMap = new HashMap<String, String>();
									Iterator<String> iterator = jsonObject.keys();
									while (iterator.hasNext()) {
										String key = iterator.next();
										String value = jsonObject.get(key) + "";
										buildMap.put(key, value);
									}
									requestList.add(buildMap);
								}
							}
								
								
								if(result.contains("floorLevel")){
									String floors = jsonobj.getString("floorLevel");
									JSONArray jsonArray = new JSONArray(floors);
									for (int i = 0; i < jsonArray.length(); i++) {
										JSONObject jsonObject = jsonArray
												.getJSONObject(i);
										HashMap<String, String> buildMap = new HashMap<String, String>();
										Iterator<String> iterator = jsonObject.keys();
										while (iterator.hasNext()) {
											String key = iterator.next();
											String value = jsonObject.get(key) + "";
											buildMap.put(key, value);
										}
										requestList.add(buildMap);
									}
							
								}
								
								if(result.contains("houseLevel")){
									String houses = jsonobj.getString("houseLevel");
									JSONArray jsonArray = new JSONArray(houses);
									for (int i = 0; i < jsonArray.length(); i++) {
										JSONObject jsonObject = jsonArray
												.getJSONObject(i);
										HashMap<String, String> buildMap = new HashMap<String, String>();
										Iterator<String> iterator = jsonObject.keys();
										while (iterator.hasNext()) {
											String key = iterator.next();
											String value = jsonObject.get(key) + "";
											buildMap.put(key, value);
										}
										requestList.add(buildMap);
									}
							
								}
						
						mHandler.obtainMessage(Config.HANDLER_MSG_GETHOUSE_SUCCESS, requestList).sendToTarget();
					} else {
						Toast.makeText(HouseChooseReuseActivity.this,
								"获取数据失败！", Toast.LENGTH_SHORT).show();
						mHandler.obtainMessage(Config.HANDLER_MSG_GETHOUSE_SUCCESS, message).sendToTarget();
					}

				} catch (Exception e) {
					e.printStackTrace();
				}

			}else {

				String message = "请设置网络";
				mHandler.obtainMessage(Config.HANDLER_MSG_GETHOUSE_FAIL,
						message).sendToTarget();

			}
			
		}
	}
	@Override
	protected void initEvents() {

		// 添加点击
		buildLv.setOnItemClickListener(new ItemClick());
		leftLayout.setOnClickListener(this);
	}

	/*
	 * item上的OnClick事件
	 */
	public final class ItemClick implements OnItemClickListener {

		public void onItemClick(AdapterView<?> parent, View arg1, int position,
				long id) {
			Map<String, String> map = requestList.get(position);
			Intent intent1 = new Intent();
			houseFullName = getHouseFullName(map);
			levelObjectId = map.get("id");
			levelCode = getLevelCode(map);
			if(null != map.get("houseName")){
				if (publicflag) {
					intent1.putExtra("houseFullName", houseFullName);
					Log.e("houseFullName", houseFullName);
					intent1.putExtra("houseId", levelObjectId);
					intent1.putExtra("repairphone","123123");
					Log.e("最后一级", "houseId = "+ map.get("id").toString());
					setResult(Config.RESULTCODE_OUTDOOR_INTENT, intent1);
					finish();
					
				}else{
					intent1.putExtra("houseFullName", houseFullName);
					Log.e("houseFullName", houseFullName);
					intent1.putExtra("houseID", levelObjectId);
					setResult(Activity.RESULT_OK, intent1);
					finish();
				}
			}else{
				
				
				Thread getdataThread = new getDataThread(levelCode, levelObjectId);
				getdataThread.start();
			}
			

		}
	}

	private String getLevelCode(Map<String, String> map){
		String levelCode = "";
		if(null != map.get("phaseName") && !map.get("phaseName").equals("")){
			levelCode = "building";
		}else if(null != map.get("buildingName") && !map.get("buildingName").equals("")){
			levelCode = "unit";
		}else if(null != map.get("unitName") && !map.get("unitName").equals("")){
			levelCode = "floor";
		}else if(null != map.get("floorName") && !map.get("floorName").equals("")){
			levelCode = "hosue";
		}else if(null != map.get("houseName") && !map.get("houseName").equals("")){
			levelCode = "";
		}
		return levelCode;
		
	}
	
	private String getHouseFullName(Map<String, String> map){
		String gethouseFullName = "";
		if(null != map.get("phaseName") && !map.get("phaseName").equals("")){
			if(map.get("phaseName").equals("0期")){
				gethouseFullName = houseFullName+"";
			}else{
				gethouseFullName = houseFullName+map.get("phaseName");
			}
		}else if(null != map.get("buildingName") && !map.get("buildingName").equals("")){
			if(map.get("buildingName").equals("0栋")){
				gethouseFullName = houseFullName+"";
			}else{
				gethouseFullName = houseFullName+map.get("buildingName");
			}
			
		}else if(null != map.get("unitName") && !map.get("unitName").equals("")){
			if(map.get("unitName").equals("0单元")){
				gethouseFullName = houseFullName+"";
			}else{
				gethouseFullName = houseFullName+map.get("unitName");
			}
			gethouseFullName = houseFullName+map.get("unitName");
		}else if(null != map.get("floorName") && !map.get("floorName").equals("")){
			if(map.get("floorName").equals("0层")){
				gethouseFullName = houseFullName+"";
			}else{
				gethouseFullName = houseFullName+map.get("floorName");
			}
			gethouseFullName = houseFullName+map.get("floorName");
		}else if(null != map.get("houseName") && !map.get("houseName").equals("")){
			gethouseFullName = houseFullName+map.get("houseName");
		}
		
		return gethouseFullName;
		
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) { // resultCode为回传的标记，我在B中回传的是RESULT_OK
		case 0:
			if (data != null) {
				this.setResult(Activity.RESULT_OK, data);
				finish();
			}
			break;
		case Config.REQUESTCODE_OUTDOOR_INTENT:
			if (requestCode == Config.REQUESTCODE_OUTDOOR_INTENT
					&& resultCode == Config.RESULTCODE_OUTDOOR_INTENT) {
				if (data != null) {
					if(null != data.getExtras().getString("houseId")){
						Log.e("楼栋houseid",data.getExtras().getString("houseId"));
					}else{
						Log.e("楼栋houseid","houseid为空");
					}
					this.setResult(Config.RESULTCODE_OUTDOOR_INTENT, data);
				} else {
					this.setResult(Config.RESULTCODE_OUTDOOR_INTENT);
				}
				this.finish();
			}
			break;
		default:
			break;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) { // 监控/拦截/屏蔽返回键
			Intent intent = new Intent();
			intent.putExtra("houseFullName", "");
			if(publicflag){
				intent.putExtra("houseId", "");
				setResult(Config.RESULTCODE_OUTDOOR_INTENT, intent);
			}else{
				intent.putExtra("houseID", "");
				setResult(Activity.RESULT_OK, intent);
			}
			finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.titlebar_left_left_layout:
			Intent intent = new Intent();
			intent.putExtra("houseFullName", "");
			if(publicflag){
				intent.putExtra("houseId", "");
				setResult(Config.RESULTCODE_OUTDOOR_INTENT, intent);
			}else{
				intent.putExtra("houseID", "");
				setResult(Activity.RESULT_OK, intent);
			}
			finish();
			break;
		}
	}
	
	
}
